<!--发布活动-->
<template>
  <div class="ele-body">
    <!--show-message 是否显示校验错误信息-->
    <el-form ref="form"
             :show-message="false"
             :model="form"
             :rules="rules"
             label-width="120px"
             @keyup.enter.native="submit"
             @submit.native.prevent>

      <el-card shadow="never">
        <div class="fit-title">返现设置</div>

        <el-row class="flex-align-center"
                :gutter="15">
          <el-col :span="8">
            <el-form-item label="现金返现:">

              <el-radio-group v-model="form.returnCashType">
                <el-radio @change="cashCashbackFn(1)"
                          :label="1">固定金额</el-radio>
                <el-radio @change="cashCashbackFn(2)"
                          :label="2">付款比例</el-radio>
              </el-radio-group>

            </el-form-item>
            <!-- <el-form-item label="挂载类型"
                          prop="sphMountType"
                          class="check-star">
              <el-radio-group v-model="form.sphMountType">
                <el-radio :label="1">公众号文章</el-radio>
                <el-radio :label="3">不挂载</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <div v-if="form.returnCashType==1">
              <el-form-item label="返现金额:"
                            prop="returnCashAmount">
                <el-input min="0"
                          type="number"
                          placeholder="请输入返现金额"
                          v-model.number="form.returnCashAmount">

                  <template slot="append">元</template>
                </el-input>

              </el-form-item>
            </div>
            <div v-if="form.returnCashType==2">
              <el-form-item label="返现比例:"
                            prop="returnCashRatio">
                <!-- <el-input min="0"
                          maxlength="100"
                          type="number"
                          v-model="form.returnCashRatio">
                  <template slot="prepend">返现</template>
                  <template slot="append">%</template>
                </el-input> -->
                <el-input min="0"
                          placeholder="请输入返现比例"
                          v-model.number="form.returnCashRatio"
                          maxlength="3">
                  <template slot="append">%</template> </el-input>
              </el-form-item>
            </div>

            <!-- <el-form-item label="返现时间:"
                          prop="returnCashTime">
              <el-input min="0"
                        type="number"
                        v-model.number="form.returnCashTime">
                <template slot="prepend">返现</template>
                <template slot="append">小时</template>
              </el-input>

            </el-form-item> -->
          </el-col>

        </el-row>

      </el-card>
      <el-card shadow="never"
               v-if="typeIndex==3"
               class="check-star">
        <div class="fit-title">卡券设置</div>

      </el-card>

      <el-card shadow="never">
        <div class="fit-title">选择素材</div>
        <div class="flex-align-center d-margin">
          <div v-for="(i,j) in materialType"
               :key="j"
               :class="(Number(form.materialType)-1) == j ? 'sel-title-class' : 'title-class'"
               class="pointer"
               @click="materialTypeClick(j)">
            {{i.name}}
          </div>
        </div>

        <el-form-item class="check-star"
                      label="文件夹"
                      prop="videoMaterialId"
                      :rules="!form.videoMaterialId  ? { required: true, message: '请选择文件夹', trigger: ['blur','change']} : {required: false}"
                      v-if="form.materialType==1">
          <div style="width: 30%;">
            <activities ref="connected"
                        :dataInfo="form"
                        :videoMaterialId="form.videoMaterialId"
                        @getData="getData"
                        :hint="hint"></activities>
          </div>
        </el-form-item>

        <el-form-item label="文件夹"
                      prop="projectName"
                      class="check-star"
                      :rules="!form.videoMaterialId  ? { required: true, message: '请选择文件夹', trigger: ['blur','change']} : {required: false}"
                      v-if="form.materialType==2">
          <div style="width: 30%;">
            <piecesCom ref="connected"
                       :dataInfo="form"
                       @getData="getData"
                       :hint="hint"></piecesCom>
          </div>
        </el-form-item>

        <!--<el-form-item label="文件夹"
                      prop="videoMaterialId"
                      :rules="!form.videoMaterialId  ? { required: true, message: '请选择文件夹', trigger: ['blur','change']} : {required: false}"
                      v-if="form.materialType==2">
          <el-select style="width: 30%;"
                     v-model="form.material"
                     placeholder="请选择文件夹"
                     class="ele-block"
                     clearable
                     @change="selectMaterial">
            <el-option :label="i.name"
                       :value="i"
                       v-for="(i,j) in cameraList"
                       :key="j" />
          </el-select>
        </el-form-item>-->

        <el-form-item label="SEO文案"
                      prop="seoCopywriting"
                      :rules="!form.seoCopywriting  ? { required: true, message: '请选择文案', trigger: ['blur','change']} : {required: false}">

          <div style="width: 30%;">
            <!--SEO文案-->
            <acties ref="seoActies"
                    :lists="seoList"
                    :seoCopywritingId="form.seoCopywritingId"
                    @getData="selectCopy"></acties>
          </div>
        </el-form-item>
      </el-card>

      <el-card shadow="never">
        <div class="fit-title">渠道与挂载</div>

        <el-form-item label="发布设置"
                      prop="shareToPublish">
          <el-radio-group v-model="form.shareToPublish">
            <el-radio :label="1">跳转到发布页（减少用户操作）</el-radio>
            <el-radio :label="0">跳转到剪辑页</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="check-star">
          <el-form-item label="挂载类型"
                        prop="mountType">
            <el-radio-group v-model="form.mountType"
                            @input="clear">
              <el-radio :label="1">商家POI</el-radio>
              <el-radio :label="2">小程序</el-radio>
              <el-radio :label="3">不挂载</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row :gutter="15"
                  class="flex-wrap no-check-star">
            <!--小程序-->
            <el-col :span="12"
                    v-if="form.mountType==2 ">
              <!--非h5传anchorUrl(挂载小程序地址)，否则传全部-->
              <el-form-item label="小程序地址"
                            prop="xcxAddress">
                <el-input style="width: 66%;"
                          class="in-append"
                          type="text"
                          v-model="form.xcxAddress"
                          placeholder="请输入小程序地址"
                          clearable>
                </el-input>
              </el-form-item>
              <!--接口需加字段 start-->
              <el-form-item label="小程序标题"
                            prop="xcxTitle">
                <el-input style="width: 66%;"
                          class="in-append"
                          type="text"
                          v-model="form.xcxTitle"
                          placeholder="请输入小程序标题"
                          clearable>
                </el-input>
              </el-form-item>
              <el-form-item label="小程序id"
                            prop="xcxId"
                            class="delInput">
                <el-input style="width: 66%;"
                          class="in-append"
                          type="text"
                          v-model="form.xcxId"
                          max="20"
                          placeholder="请输入小程序id"
                          clearable>
                </el-input>
              </el-form-item>
              <!--end-->
            </el-col>

            <el-col :span="12"
                    v-if="form.mountType==1">
              <el-form-item label="城市"
                            prop="provinceCity">
                <!-- type="provinceCity" 增加type 是省市选择，不加，默认省市区选择-->
                <!-- placeholder：报错需修改-->
                <regions-select @input="selectCity"
                                :placeholder="provinceCity ?provinceCity :'请选择省市'"
                                style="width: 66% !important;"
                                v-model="provinceCity"
                                type="provinceCity"
                                class="ele-fluid" />
              </el-form-item>
              <el-form-item label="商家简称"
                            prop="merchantAbbreviation">
                <el-input style="width: 66%;"
                          class="in-append"
                          type="text"
                          v-model="form.merchantAbbreviation"
                          placeholder="请输入商家简称"
                          clearable>
                  <el-button slot="append"
                             icon="el-icon-search"
                             @click="seachPoi"
                             :loading="poiLoading"></el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="POI地址"
                            prop="poiName">
                <el-select style="width: 66%;"
                           v-model="form.poiName"
                           placeholder="请输入城市和商家简称搜索可加载"
                           class="ele-block"
                           clearable
                           @visible-change="showChange"
                           @change="addressPoi">
                  <div v-for="(i,j) in poiList"
                       :key="j">
                    <!--修改11-->
                    <el-option style="min-width:300px;max-width: 600px;"
                               :label="i.poi_name"
                               :value="i" />
                  </div>
                  <el-button type="text"
                             style="padding:10px 20px ;color: #409EFF"
                             @click="lookMore()"
                             :loading="poiLoading"
                             v-if="nextStep!=-1">查看更多</el-button>
                  <div v-else
                       class="m-out">已经到底了~</div>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 视频号-->
        <el-row :gutter="15"
                v-if="form.releaseChannel==2">
          <el-form-item label="挂载类型"
                        prop="sphMountType"
                        class="check-star">
            <el-radio-group v-model="form.sphMountType">
              <el-radio :label="1">公众号文章</el-radio>
              <el-radio :label="3">不挂载</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-col :span="12"
                  class="no-check-star"
                  v-if="form.sphMountType==1">
            <el-form-item label="链接"
                          prop="sphLink">
              <el-input class="in-append"
                        type="text"
                        style="width: 66%;"
                        v-model="form.sphLink"
                        placeholder="请输入链接地址"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!--        K手-->
        <el-row :gutter="15"
                v-if="form.releaseChannel==3">
          <el-col :span="12">
            <el-form-item label="挂载小黄车"
                          prop="littleYellowCarId">
              <el-input style="width: 66%;"
                        class="in-append delInput"
                        type="number"
                        oninput="value=value.replace(/[^0-9]/g,'')"
                        v-model.number="form.littleYellowCarId"
                        placeholder="请输入需要挂载小黄车的商品ID"
                        clearable>
              </el-input>
              <el-link type="primary"
                       style="margin-left: 17px;">如何获取商品ID<i class="el-icon-question"></i> </el-link>
            </el-form-item>
          </el-col>
        </el-row>

        <el-button type="primary"
                   class="m-left10"
                   @click="confirm"
                   :loading="loading"
                   v-if="typeIndex==0 || typeIndex==3 || typeIndex==4">确定提交</el-button>
      </el-card>
      <!-- 奖品列表 -->
      <prize ref="prize"
             v-if="typeIndex==1 || typeIndex==2"
             :forms="form"
             @uploadPrice="uploadPrice"></prize>
    </el-form>
  </div>
</template>

  <script>
import activities from '@/components/activities/connected-activities'
import acties from '@/components/pagination/activities'
import piecesCom from '@/components/activities/pieces-activities'

// import RegionsSelect from '@/components/RegionsSelect/index.vue';
import { addActivityconfig, updateActivityconfig, getActivityconfig } from '@/api/douPayActivityConfiguration/index.js'
import RegionsSelect from './components/city-select'
import prize from './components/prize.vue'
import { issue, submitProjectJob, submitDiyJob, submitImageJob, incomingParts } from "@/api/explosiveCode/releaseActivity";
import { listUserFiles, publicFile, registerMedia, userOssSignature } from "@/api/creatCenter/material";
import { getToken } from "@/utils/token-util";
import axios from "axios";
import { getByUndistributed } from "@/api/explosiveCode/equipmentManage";
import { projectPage } from "@/api/creatCenter/authoringClips";
import { querySeo } from "@/api/matrixManage/seo";
import { queryGroup } from "@/api/matrixManage/groupManage";
import { dyPoi } from "@/api/releaseManage/tiktok";
import selectPagination from "@/components/pagination/select-pagination"
export default {
  name: "index",
  components: { prize, RegionsSelect, selectPagination, activities, acties, piecesCom },
  data () {
    // 默认表单数据
    const defaultWhere = {

      // 返现时间
      returnCashTime: 24,
      //  返现比例
      returnCashRatio: '',
      //   返现金额
      returnCashAmount: '',
      // 返回类型
      returnCashType: 1,
      //   authorizedNot: 1, // 是否默认授权发布  1.否 2.是
      //   douPayNot: 2, // 抖支付开启：2，默认不开启：1，开启
      merchantId: this.$store.state.user.info.merchantId,  // 商户id

      // id: this.$store.state.user.info.merchantId,
      //   activityType: 1,
      //   // 云创作成片库/云闪推成片库，分类
      //   商家简称
      merchantAbbreviation: '',
      // poid地址
      cityName: '',
      poiName: '',
      poiId: '',
      materialType: 1,
      videoMaterialId: '',
      city: '',
      videoMaterial: null, //剪辑工程名
      seoCopywritingId: '',//SEO ID
      seoCopywriting: '', //SEO名称
      //   // 剪辑类型
      //   // clipType:2,
      //   // 奖品类型
      //   prizeLists: {
      //     firstPrize: 1
      //   },
      //   // 卡劵类型
      //   cardsettings: {
      //     cardType: 1,
      //   },
      //   // 发布渠道
      releaseChannel: 1,
      //   // 挂载类型
      mountType: 1,
      //   // 视频号——公众号文章 挂载
      //   sphMountType: 1,
      shareToPublish: 1, //发布设置 必填
      //   小程序链接
      xcxAddress: null,
      //   小程序标题
      xcxTitle: null,
      //   小程序地址
      xcxId: null
    };
    return {
      isUpdata: false,
      materialType: [
        {
          name: '云创作成片库',
          id: 1
        },
        {
          name: '云闪推成片库',
          id: 2
        }
      ],
      nextStep: '0',   // 是否有 “游标第一页”
      // 回显值
      initValue: undefined,
      //page start
      agencyList: [], // 放数据的数组儿
      // 请求参数
      agency: {
        pageNum: 1,
        pageSize: 8,
        condition: "",  // 输入框儿输入申请符合条件的数据
      },
      totalAgency: 0, // 分页的总数儿
      agencyLoading: false,  // 列表儿的loading圈儿~
      //page end
      poiLoading: false,
      loading: false,
      // 日期设置对象
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7;   //禁用以前的日期，今天不禁用
          // return time.getTime() <= Date.now();    //禁用今天以及以前的日期
        }
      },
      options: [{
        value: 'zhinan',
        label: '指南',
        children: [{
          value: 'shejiyuanze',
          label: '设计原则',
        }]
      }],
      // 省市
      provinceCity: '',
      // POI地址
      poiList: [],
      list: [],
      // seo 列表
      seoList: [],
      // 上传背景图片url
      fileList: [],
      name: '',
      // 背景图
      imageUrl: '',
      form: { ...defaultWhere },
      typeIndex: 0,
      // 发布渠道
      channelIndex: 0,
      typeList: [
        {
          name: '视频快推',
          id: 1
        },
        {
          name: '幸运大转盘',
          id: 2
        },
        {
          name: '幸运九宫格',
          id: 3
        },
        {
          name: '卡券活动',
          id: 4
        },
        {
          name: '爆客机设备',
          id: 5
        },
      ],
      // 卡券分类
      couponType: [
        {
          name: '折扣券',
          id: 1
        },
        {
          name: '满减券',
          id: 2
        },
        {
          name: '礼品券',
          id: 3
        },
        {
          name: '红包券',
          id: 4
        },
      ],
      channelList: [
        {
          name: 'D音',
          id: 1,
          isShow: 2
        },
        // {
        //   name: '视频号',
        //   id: 2,
        //   isShow: 1
        // },
        // {
        //   name: 'K手',
        //   id: 3,
        //   isShow: 2
        // },
      ],
      // 表单验证规则
      rules: {
        activityName: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur'
          }
        ],
        activityDescription: [
          {
            required: true,
            message: '请输入活动说明',
            trigger: 'blur'
          }
        ],
        dailyAvailability: [
          {
            required: true,
            message: '请输入每人一天可领取数量',
            trigger: 'blur'
          }
        ],
        perPerson: [
          {
            required: true,
            message: '请输入限领取数量',
            trigger: 'blur'
          }
        ],
        validTime: [
          {
            required: true,
            message: '请选择有效时间',
            trigger: 'blur'
          }
        ],
        videoMaterialId: [
          {
            required: true,
            message: '请选择文件夹',
            trigger: 'blur'
          }
        ],
        /* editingNumber: [
         {
         required: true,
         message: '请输入剪辑数量',
         trigger: 'blur'
         }
       ],*/
        seoCopywriting: [
          {
            required: true,
            message: '请选择SEO文案',
            trigger: 'blur'
          }
        ],
        /*shareToPublish: [
          {
          required: true,
          message: '请选择发布设置',
          trigger: 'blur'
          }
        ],*/
        // 挂载类型——小程序
        // xcxAddress: [
        //   {
        //     required: true,
        //     message: '请输入小程序地址',
        //     trigger: 'blur'
        //   }
        // ],
        // xcxTitle: [
        //   {
        //     required: true,
        //     message: '请输入小程序标题',
        //     trigger: 'blur'
        //   }
        // ],
        // xcxId: [
        //   {
        //     required: true,
        //     message: '请输入小程序id',
        //     trigger: 'blur'
        //   }
        // ],
        //  挂载类型 —— poi
        city: [
          {
            required: true,
            message: '请选择省市',
            trigger: 'blur'
          }
        ],



        // littleYellowCarId: [
        //   {
        //     required: true,
        //     message: '请输入需要挂载小黄车的商品ID',
        //     trigger: 'blur'
        //   }
        // ],

        /*卡券设置 嵌套判断 */
        // cardsettings: {
        //   numberOfReleases: [
        //     {
        //       required: true,
        //       message: '输入发布数量',
        //       trigger: 'blur'
        //     }
        //   ],
        //   perPersonLimit: [
        //     {
        //       required: true,
        //       message: '输入限领取数量',
        //       trigger: 'blur'
        //     }
        //   ],
        //   dailyAvailability: [
        //     {
        //       required: true,
        //       message: '输入每人一天可领取数量',
        //       trigger: 'blur'
        //     }
        //   ],
        //   writeOffTime: [
        //     {
        //       required: true,
        //       message: '选择核销开始时间',
        //       trigger: 'blur'
        //     }
        //   ],
        //   checkEndTime: [
        //     {
        //       required: true,
        //       message: '选择核销结束时间',
        //       trigger: 'blur'
        //     }
        //   ],
        // },
        /* ‘奖品设置’ 嵌套判断*/
        // prizeLists: {
        //   firstPrize: [
        //     {
        //       required: true,
        //       message: '请输入一等奖奖项',
        //       trigger: 'blur'
        //     }
        //   ],
        //   secondClassPrize: [
        //     {
        //       required: true,
        //       message: '请输入二等奖奖项',
        //       trigger: 'blur'
        //     }
        //   ],
        //   theThirdPrize: [
        //     {
        //       required: true,
        //       message: '请输入三等奖奖项',
        //       trigger: 'blur'
        //     }
        //   ],
        //   theFourthPrize: [
        //     {
        //       required: true,
        //       message: '请输入四等奖奖项',
        //       trigger: 'blur'
        //     }
        //   ],
        //   theFifthPrize: [
        //     {
        //       required: true,
        //       message: '请输入五等奖奖项',
        //       trigger: 'blur'
        //     }
        //   ],
        // },
        //选择设备
        equipmentName: [
          {
            required: true,
            message: '请选择设备',
            trigger: 'blur'
          }
        ],
      },
      initInfo: {
        username: this.$store.state.user.info.username,
        limit: 5,
        page: 1
      },
      seoInfo: {
        username: this.$store.state.user.info.username,
        limit: 10,
        page: 1,
        // seo 所属平台：1D音2K手3视频号
        platform: 1
      },
      // 是否路由调转
      isRoute: false,
      // ‘闲置中’设备查询
      deviceList: [],

      /* el-select 分页 start*/
      options: [],
      optionfen: [],  //当前页码的数据
      value1: "",  //输入框的值
      currentpage: 1,   //当前页码
      pageSize: 5,   //每页展示的条数
      /* el-select 分页 end*/
      hint: '',
      maxNum: 0  // 关联活动最大剪辑数量
    }
  },
  // 路由刷新
  activated () {


    setTimeout(() => {
      this.init()
    }, 500)
    this.seoInit()



    console.log('created11111111111111111', this.form.clipTypes)
    this.$nextTick(() => {
      this.$refs['connected'].init(this.form.clipType)
    })

    this.queryEquipment()
    // this.isIncomingParts()  已弃用，查询抖支付是否进件完成筛选
    // 工作台跳转
    if (this.$route.query.typeIndex) {
      this.isRoute = false
      console.log("工作台路由切换=====")
      this.typeIndex = this.$route.query.typeIndex
      //   this.form.activityType = this.typeList[this.typeIndex].id
      return
    }
    else if (this.$route.query.row) {
      this.isRoute = true
      console.log("活动列表路由切换=====")
      this.form = this.$route.query.row
      this.channelIndex = this.form.releaseChannel - 1
      this.provinceCity = this.form.cityName  //城市
      //   this.typeIndex = Number(this.form.activityType) - 1
      // this.projectInit(this.form.clipType)
      return
      // this.imageUrl=this.form.backgroundImage  暂时隐藏背景图
    }
    else {
      this.channelIndex = 0
      this.isRoute = false
      console.log("进入else================")
      // 新增参数 也需要在此添加

    }
  },
  created () {
    /*this.seoInit()
    this.queryEquipment()*/
  },
  mounted () {
    // this.getAgency();
  },
  methods: {
    async init () {
      //   this.form.seoCopywritingId = 224
      //   this.form.videoMaterialId = 1565

      const msg = await getActivityconfig({
        merchantId: this.$store.state.user.info.merchantId,
        page: 1,
        limit: 10
      })

      if (msg) {
        //   是修改
        console.log(msg)
        if (msg.code == 2000) {

          if (msg.data.list.length) {
            const listObect = msg.data.list[0]
            console.log(listObect)
            this.$util.assignObject(this.form, {
              ...listObect
            });
            this.form.id = listObect.id;
            this.form.returnCashType = Number(listObect.returnCashType)
            console.log(this.form)
            this.isUpdata = true;
            this.provinceCity = listObect.cityName
            this.form.seoCopywritingId = listObect.seoCopywritingId
          } else {
            // 添加
            this.isUpdata = false;
          }

        }


      }


    },
    // 切换 ‘类型’
    materialTypeClick (e) {
      // 素材类型 1.云创作成片库 2.云闪推成片库
      this.form.materialType = this.materialType[e].id
      this.form.videoMaterialId = ''
    },
    // 获取是否已进件，applymentState为2则开启“ 抖支付 ”
    isIncomingParts () {
      incomingParts({
        id: this.$store.state.user.info.merchantId,  // 商户id
      })
        .then((data) => {
          console.log("data.data", data)
        })
        .catch((e) => {
          this.$message.error(e);
        });
    },
    // 获取“关联活动”
    getData (e) {
      this.$set(this.form, 'videoMaterialId', e?.id) //剪辑工程ID

      // 1:云创作成片库 2：云闪推成片库
      if (this.form.materialType == 2) {
        this.form.videoMaterial = e.projectName //剪辑工程名
        this.maxNum = e.jjCount
      }
      else {
        this.form.videoMaterial = e.name //剪辑工程名
        // this.maxNum=e.max
        // 剩余剪辑数量
        this.maxNum = e.max - e.montageCount
      }
      console.log("this.form=============", this.form, 'e', e)
    },
    // page start
    getAgency (val) {
      console.log("val-----", val)
      this.agencyLoading = true;
      // 清空
      if (this.form.videoMaterialId) {
        delete this.form.videoMaterialId     //剪辑工程ID
        delete this.form.videoMaterial   //剪辑工程名
      }
      Object.assign(this.initInfo, {
        // 1:脚本剪辑 2:自定义剪辑 3:图文剪辑
        type: this.form.clipType
      })
      // 活动名称
      projectPage(this.initInfo)
        .then((data) => {
          console.log("data.data", data)
          this.agencyList = data.list;
          this.totalAgency = data.count;
          this.agencyLoading = false;
          console.log("this.agencyList", this.agencyList)
        })
        .catch((e) => {
          this.$message("暂无机构");
          this.agencyList = [];
          this.totalAgency = 0;
          this.agencyLoading = false;
          console.log("进入catch======", e)
          this.$message.error(e);
        });
    },
    cashCashbackFn (index) {
      if (index == '1') {
        this.form.returnCashType = index;
        // 是否为固定金额
        this.form.returnCashRatio = ''
      } else {
        this.form.returnCashType = index;
        this.form.returnCashAmount = ''
      }
    },
    getAgency2 () {
      this.agencyLoading = true;
      //  getAgencyList 为接口名儿
      // this.agency是请求参数的对象儿
      getAgencyList(this.agency).then((res) => {
        if (res.code == 200 && res.success) {
          this.agencyList = res.content;
          this.totalAgency = res.totalCount;
          this.agencyLoading = false;
        } else {
          this.$message("暂无机构");
          this.agencyList = [];
          this.totalAgency = 0;
          this.agencyLoading = false;
        }
      });
    },
    // 暂未使用
    changeAgencyInput (value) {
      if (value == "") {
        // 如果输入框儿为空则清空之前选中机构后赋值的参数
        this.listQuery.code = "";
        this.agency.condition = "";
        this.getAgency();
      } else {
        // 赋值
        this.agency.condition = value;
        this.getAgency();
      }
    },
    //end

    // el-select 分页
    handleCurrentChange (val) {
      console.log("this.currentpage", this.currentpage)
      console.log("进入el-select 分页点击========", val)
      this.list = [];
      this.currentpage = val;
      this.initInfo.page = val
      // this.projectInit()
      /*let start = (val - 1) * this.pageSize;
      let end = Number(start) + Number(this.pageSize);
      //此处需要判断如果计算的结束下标大于总数据的长度，则需要修改结束下标
      if (end > this.options.length) {
      end = this.options.length;
      }
      for (let i = start; i < end; i++) {
      //将取到的数据展示在页面
      this.list.push(this.options[i]);
      }*/
      // this.optionfen=this.options
    },
    //查询设备
    queryEquipment () {


      // 暂不调用该接口，需要改好，检查对应字段是否正确，赋值
      return
      getByUndistributed(this.$store.state.user.info.merchantId)
        .then((data) => {
          this.deviceList = data.data
          console.log("查询设备--data=======", data)
        })
        .catch((e) => {
          this.$message.error(e);
        });
    },
    /*projectInit(){
      // 清空
      if(this.form.videoMaterial){
      this.form.videoMaterialId=''     //剪辑工程ID
      delete this.form.videoMaterial   //剪辑工程名
      }
      this.$nextTick(() => {
      this.$refs['connected'].init(this.form.clipType)
      })
      return

      // 活动名称
      projectPage(this.initInfo)
      .then((data) => {
        this.list=data.list;
        this.tableConfig.datasource = this.list;
        console.log("this.list",this.list)
      })
      .catch((e) => {
        console.log("进入catch======",e)
        this.$message.error(e);
      });
    },*/
    seoInit () {
      if (this.form.seoCopywriting) {
        // delete this.form.seoCopywritingId
        this.$set(this.form, 'seoCopywriting', '')  //SEO名称
        // delete this.form.seoCopywriting
        // this.$refs['seoActies'].clear()
      }
      this.querySeoList()
    },
    querySeoList () {
      // 查询SEO文案【分页查询】 在查询列表页使用
      querySeo(this.seoInfo)
        .then((data) => {
          console.log('data.', data)
          this.seoList = data.list
          this.$nextTick(() => {
            this.$refs['seoActies'].init()
          })
        })
        .catch((e) => {
          console.log("进入catch111111======", e)
          this.$message.error(e.msg);
        });
    },
    //搜索poi地址(下一页需要传入‘游标’字段，注意修改
    seachPoi () {
      // 商家地址选择this.provinceCity[1].value,  0:省 1：市
      console.log(this.form.city)
      console.log("商家地址this.provinceCity=======", this.provinceCity, '商家简称merchantName', this.form.merchantAbbreviation)

      if (!this.provinceCity) {
        this.$message.warning("请选择省市")
        return
      }
      if (!this.form.merchantAbbreviation) {
        this.$message.warning("请输入商家简称")
        return
      }
      this.poiLoading = true
      this.nextStep = '0' // 重新搜索则游标归0
      console.log(this.form.city)
      if (!this.form.city) {
        this.form.city = this.provinceCity[1].value


        this.form.cityName = this.provinceCity[0].label + '/' + this.provinceCity[1].label

      }
      this.datasource(this.nextStep, 10)
    },
    datasource (page, limit) {
      dyPoi(this.form.merchantAbbreviation, this.form.city, page, limit)
        .then((data) => {
          this.poiLoading = false
          console.log("this.nextStep", this.nextStep)
          if (this.nextStep == 0) {
            this.poiList = data.data.pois ? data.data.pois : []
            if (this.poiList.length <= 0) {
              return
            }
            this.form.poiName = this.poiList[0].poi_name // 赋值poi地址（修改11）
            this.form.poiId = this.poiList[0].poi_id  //POI ID
            console.log('设置poiName1111111111111')
          }
          else {
            if (data.data.pois) {
              this.poiList = [...this.poiList, ...data.data.pois]
            }
          }
          /*has_more:是否有下一页
          cursor:游标第一页为0，后续页游标在响应数据中获取*/
          this.nextStep = data.data.has_more == false ? -1 : data.data.cursor
        })
        .catch((e) => {
          this.poiLoading = false
          this.$message.error(e);
        });


    },
    // 查看更多
    lookMore () {
      this.poiLoading = true
      this.datasource(this.nextStep, 10)
    },
    // 城市选择
    selectCity (e) {
      console.log("城市选择e=====", e)
      console.log("provinceCity", this.provinceCity, this.form)
      this.form.city = e[1].value
      this.form.cityName = e[0].label + '/' + e[1].label
      this.clearPoi(1)
    },
    // // 商家简称输入
    // referred (e) {
    //   console.log("商家简称输入=====", e)
    //   this.clearPoi(2)
    // },
    // 清空POI地址
    clearPoi (type) {
      // type 1:城市 2:商家简称
      if (this.form.poiId && type == 1) {  // 清空poi地址文本并清空poiId
        delete this.form.poiId
        if (this.provinceCity.length <= 0) {
          this.provinceCity = '' // 清除城市文本，在搜索前提示
        }
        this.$set(this.form, 'poiName', '')
      }
      this.poiList = []
      if (this.form.poiName) {
        this.$message.warning("请重新搜索")
      }
      delete this.form.poiName // 清空poi地址文本 和poi地址list
    },
    // POI地址
    addressPoi (e) {
      this.form.poiId = e.poi_id  //POI ID
      //   this.$delete(this.form, 'poiName')
      this.$set(this.form, 'poiName', e.poi_name) //POI 名称（修改11）
      console.log("POI地址e-------", e, 'this.form', this.form, this.form.poiName)
    },
    showChange (e) {
      console.log(this.form.poiName)
      if (e) {
        if (this.form.poiName) {
          this.datasource(this.nextStep, 10)
        }
      }
    },
    // 选择有效时间
    selTime (e) {
      console.log('selTime=======', e)
      // msToDate: 中国标准时间转化为年月日
      this.$set(this.form, 'validTime', this.$sun.msToDate(e))
      // this.form.validTime= this.$sun.msToDate(e)
      console.log('this.msToDate(e)22222222222', this.$sun.msToDate(e))
    },
    // 选择 视频素材
    selectVideo (e) {
      console.log('选择 视频素材', e)
      this.form.videoMaterialId = e.id //剪辑工程ID
      this.form.videoMaterial = e.name //剪辑工程名
    },
    // 选择 “闲置中” 的设备管理
    selectDevice (e) {
      console.log('选择的设备管理', e)
      this.form.equipmentId = e.id
      this.form.equipmentName = e.equipmentName
    },
    // 选择SEO文案
    // 获取“seo文案”
    selectCopy (e) {
      console.log('选择文案', e)
      this.form.seoCopywritingId = e?.id //SEO ID
      this.form.seoCopywriting = e?.taticsName //SEO名称
      console.log('this.form=======', this.form)
    },

    /* 上传 */
    onUpload (file) {
      this.fileList.push(file)
      console.log('this.fileList', this.fileList)
    },
    async uploadBj () {
      if (this.fileList.length < 1) {
        if (this.imageUrl) {
          this.$message.error('重复文件');
        }
        else {
          this.$message.error('请选择文件后提交');
        }
      }
      // 获取文件上传签名数据
      this.data = await userOssSignature()
      for (let i = 0; i < this.fileList.length; i++) {
        let file = this.fileList[i].raw
        let filename = file.name;
        let markIndex = (filename).lastIndexOf('.');
        let suffix = filename.substring(markIndex)    // 图片后缀(例.jpg)
        let date = new Date().getTime();    // 当前时间戳
        // 构建请求参数
        let param = new FormData()
        param.append("key", this.data.dir + date + suffix)
        param.append("policy", this.data.policy)
        param.append("OSSAccessKeyId", this.data.accessId)
        param.append("success_action_status", '200')
        // param.append("callback",  this.data.callback)     //回调（not)
        param.append("signature", this.data.signature)
        param.append("file", file, file.name)
        param.append('success_action_status', '200')
        let config = {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'x-oss-callback-Authorization': getToken()
          }
        }
        axios.post(this.data.host, param, config).then(res => {
          if (res.status == 200) {
            console.log('this.data.host', this.data.host + '/' + date + suffix)
            let url = this.data.host + '/' + date + suffix;
            this.form.backgroundImage = url;
            let type = file.type;
            this.fileList = []
          }
          else {
            this.$message.error('上传失败');
          }

        }).catch(err => {
          console.log(err)
        })
      }
    },

    registerMedias (url, type) {
      registerMedia({
        mediaUrl: url,//上传阿里云生成的地址
        mediaType: type,//文件类型
        username: this.$store.state.user.info.username,
        folderId: this.parentId

      })
        .then((data) => {
          this.$message.success('上传成功');
          //关闭弹窗
          this.updateVisible(false);
          // this.$message.success(data.msg);
          this.onDone();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    // 切换 ‘活动类型’ ：类型（1.视频快推2.幸运大转盘3.幸运九宫格4.卡劵活动）
    typeClick (e) {
      // 从上个页面路由进入，则不能点击切换该按钮
      if (this.isRoute == true) {
        return
      }
      this.form.authorizedNot = 1 // 是否默认授权发布——恢复默认不选择
      this.typeIndex = e;
      this.seoInfo.platform = 1   // 选择素材——所属平台
      // 渠道与挂载——发布类型 start
      this.channelIndex = 0
      this.form.releaseChannel = 1
      // end
      this.$set(this.form, 'activityType', this.typeList[e].id)
      this.$nextTick(() => {
        this.$refs['prize'].init(this.form);
      })
      // this.form.activityType=this.typeList[e].id
    },
    // “剪辑数量”输入事件 （修改）
    /* maxClick(e){
     console.log(' “剪辑数量”输入事件',e)
     if(this.maxNum>0 && this.maxNum<e){
     this.form.editingNumber = this.maxNum
     }
   },*/

    // 发布渠道
    channelClick (e) {
      this.channelIndex = e
      this.form.releaseChannel = this.channelList[e].id
      if (e > 0) {
        this.form.authorizedNot = 1
      }
      // 渠道为快手——暂未使用
      /*if(e==2){
      this.appletClear()
      this.form.mountType=2
      }
      else{
      if(e==0){
        this.appletClear()
      }
      this.form.mountType=1
      }*/
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      // const isJPG = file.type === 'image/jpeg';
      const isJPG = file.type;
      const isLt2M = file.size / 1024 / 1024 < 2;

      const extension1 = file.type === "image/jpg";
      const extension2 = file.type === "image/jpeg";
      const extension3 = file.type === "image/png";
      if (!extension1 && !extension2 && !extension3) {
        this.$message.error("请上传jpg 、png、jpeg 类型图片!");
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 幸运大转盘/九宫格 提交
    uploadPrice (e) {
      console.log('e', e)
      // return
      this.form.listofprizes = e
      this.confirm()
    },
    // 确定提交
    confirm () {
      console.log("this.form", this.form)

      //   if (!this.form.authorizedNot) {
      //     this.$set(this.form, 'authorizedNot', 1)
      //   }
      //   this.$set(this.form, 'douPayNot', 2) // 抖支付开启：2，默认不开启：1，开启
      //   console.log("路由切换activated=====", this.form, 'this.form.validTime', this.form.validTime, 'this.form.cardsettings.checkEndTime', this.form.cardsettings.checkEndTime)

      /*if(this.form.videoMaterialId){
        this.$refs["form"].clearValidate(["videoMaterialId"]);
      }
      if(this.form.videoMaterialId){
      console.log("11111111111111")
      // this.rules.videoMaterialId[0].required=false
      this.$set(this.rules.videoMaterialId[0], 'required', false)
      console.log('this.rules',this.rules)
      }
      else {
      console.log("12222222222222")
      // let info=[{message:''}]
      this.$set(this.rules.videoMaterialId[0], 'required', true)
      // this.rules.videoMaterialId[0].required=true
      }*/
      console.log("this.rules222", this.rules)
      this.$refs.form.validate((valid, obj) => {

        // for (let i in obj) {
        //   console.log("i", i)
        //   console.log("obj=========", obj[i][0].message)
        //   this.hint = obj[i][0].message
        //   break
        // }

        if (valid) {
          // 修改1
          if (!this.form.videoMaterialId) {
            this.hint = '请选择文件夹'
            this.$message.error(this.hint)
            return
          }

          //   if (this.form.releaseChannel != 1) {
          //     delete this.form.shareToPublish
          //   }



          //   if (this.form.releaseChannel == 1) {
          //     this.wananchiClear()
          //     if (this.form.mountType == 1) {
          //       this.appletClear()
          //     }
          //     if (this.form.mountType == 2) {
          //       this.poiClear()
          //     }
          //     if (this.form.mountType == 3) {
          //       this.appletClear()
          //       this.poiClear()
          //     }
          //   }
          //   if (this.form.releaseChannel == 2) {
          //     this.appletClear()
          //     this.poiClear()
          //   }
          //   if (this.form.releaseChannel == 3) {

          //     this.appletClear()
          //     this.poiClear()
          //     this.wananchiClear()
          //   }
          if (this.form.mountType == 2) {
            if (!(this.form.xcxAddress && this.form.xcxId && this.form.xcxTitle)) {
              this.$message.error('请填写小程序的必要参数')
              return
            }
          }
          if (this.form.mountType == 1) {
            if (!(this.form.poiName && this.form.merchantAbbreviation && this.form.cityName)) {
              console.log('请填写poi地址的必要参数')
              this.$message.error('请填写poi地址的必要参数')
              return
            }
          }
          if (!(this.form.returnCashRatio || this.form.returnCashAmount)) {
            this.$message.error('请输入返现比例或者返现金额')
            return
          }
          if (!this.form.seoCopywriting) {
            this.$message.error('请选择seo文案')
            return
          }
          this.issues()
          console.log(this.form)
        } else {
          console.log("进入非空提示", valid, '22', this.form)
          this.$message.error('请填写必要参数')
          return false;
        }
      });
    },
    // D音——小程序删除
    appletClear () {
      delete this.form.xcxAddress
      delete this.form.xcxTitle
      delete this.form.xcxId
    },
    // D音——POI删除
    poiClear () {
      delete this.form.merchantAbbreviation
      delete this.form.poiName
      delete this.form.cityName
      delete this.form.city
      delete this.provinceCity
    },
    // 视频号——公众号文章 清空
    wananchiClear () {
      this.form.sphLink = ''
      delete this.form.sphLink
    },
    clear () {
      if (this.form.mountType == 2) {
        this.form.merchantAbbreviation = ''
        this.form.poiName = ''
        this.form.cityName = ''
        this.form.city = ''
        this.provinceCity = ''
      }
      if (this.form.mountType == 1) {
        this.form.xcxAddress = ''
        this.form.xcxTitle = ''
        this.form.xcxId = ''
      }
      if (this.form.mountType == 3) {
        this.form.merchantAbbreviation = ''
        this.form.poiName = ''
        this.form.cityName = ''
        this.form.city = ''
        this.provinceCity = ''

        this.form.xcxAddress = ''
        this.form.xcxTitle = ''
        this.form.xcxId = ''
      }
      console.log("this.form", this.form)
    },
    issues () {
      // if(this.form.activityType!=4){
      //   delete this.form.cardsettings
      // }


      console.log("this.form", this.form)
      const saveOrUpdate = this.isUpdata ? updateActivityconfig : addActivityconfig;
      //   if (this.isUpdata) {
      //     delete this.form.merchantId
      //   }
      this.form.returnCashTime = 24
      this.loading = true
      saveOrUpdate(this.form)
        .then((data) => {
          this.$message.success('提交成功！')
          this.loading = false
          //   this.clean()
          console.log("确定提交22222222222", data, 'this.form======', this.form)

          //   this.form.materialType = 1
          setTimeout(() => {
            this.init()
          }, 500)
          // this.submitTo()
        })
        .catch((e) => {
          console.log('进入失败', e)
          this.$message.error(e);
        });

    },
    //  提交——由于“创作剪辑”已生成，隐藏不需要再次调用混剪接口，未使用
    submitTo () {
      // <!-- * 1脚本剪辑 =AI剪辑 * 2自定义剪辑=口播剪辑 * 3图文剪辑-->
      const typeApi = this.form.clipType == 1 ? submitProjectJob : this.form.clipType == 2 ? submitDiyJob : submitImageJob
      typeApi({
        id: this.form.videoMaterialId,//剪辑工程主键ID
        maximumCount: this.form.editingNumber, //剪辑工程所属用户
        username: this.$store.state.user.info.username
      })
        .then((data) => {
          this.$message.success('提交成功！')
          this.clean()
          console.log("确定提交22222222222", data, 'this.form======', this.form)
        })
        .catch((e) => {
          this.clean()
          this.$message.error(e);
        });
    },
    clean () {
      this.$nextTick(() => {
        // 且勿滥用
        this.$refs.form.resetFields()
        delete this.form.backgroundImage
        delete this.form.cityName
        this.channelIndex = 0
        this.typeIndex = 0  // 视频快推分类清零
        this.form.releaseChannel = 1
        this.form.shareToPublish = 1  // 抖音发布设置
        this.seoInfo.platform = 1   // seo平台默认抖音
        this.form.mountType = 1    //挂载类型
        this.hint = ''                // 修改1
        this.provinceCity = ''
        this.imageUrl = ''
        // 调佣子组件 ‘清空form’ 方法
        if (this.typeIndex == 1 || this.typeIndex == 2) {
          this.$nextTick(() => {
            this.$refs['prize'].refresh();
          })
        }
      })
      this.loading = false
      this.$nextTick(() => {
        this.$refs['connected'].init(this.form.clipType)
        // this.$refs['connected'].clear()
        // this.$refs['seoActies'].clear()
        this.querySeoList()
      })
    }
  }
}
  </script>

  <style lang="less" scoped>
/*隐藏input（type=number)右边的小箭头*/
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}

.tiktok-title {
  padding: 5px 0 30px;
  font-size: 20px;
  color: #000000;
}
.title-class,
.sel-title-class,
.no-title-class {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 21px;
  width: 114px;
  height: 35px;
  border-radius: 5px;
}
.no-title-class {
  cursor: not-allowed;
  /*cursor:no-drop;*/
  /*color: #969696;
	  background: #4c4c4c;*/
  /*编辑——进入不可选*/
  color: #c9c9c9;
  background: #f9f9f9;
}
.title-class {
  color: #757575;
  background: #fafafc;
}
.sel-title-class {
  color: #1e6ceb;
  background: #ddf0ff;
}
.fit-title {
  color: #333333;
  font-size: 16px;
  margin: 0px 2px 20px;
}

/*云创作成片库/云闪推成片库 style */
.d-margin {
  margin-left: 38px;
  margin-bottom: 22px;
}
.title-class,
.sel-title-class {
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 21px;
  min-width: 100px;
  padding: 0 15px;
  height: 35px;
  border-radius: 5px;
}
.title-class {
  color: #757575;
  background: #fafafc;
}
.sel-title-class {
  color: #1e6ceb;
  background: #ddf0ff;
}
/*end*/

.xy-border {
  padding-top: 41px;
  border-top: 1px solid #ececec;
  margin-top: 22px;
}
.upload-class {
  margin: -16px 0 2px;
  div {
    line-height: 18px;
    color: #757575;
  }
}
/*  ‘背景图’上传 start */
.avatar-uploader {
  margin: 0;
  padding: 0;
  outline: none;

  /* 修改 start*/
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  /*end*/
  width: 88px;
  height: 88px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  color: #d9d9d9;
  text-align: center;
  i {
    font-size: 28px;
  }
  div {
    padding-top: 3px;
  }
}
.avatar {
  width: 90px;
  height: 90px;
  display: block;
}
/*  end*/
</style>
